package com.dewod.producesales.utils;

import android.util.Log;

import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.NameValuePair;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.ParseException;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.client.entity.UrlEncodedFormEntity;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.message.BasicNameValuePair;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.http2.Header;

public class HttpUtil {

    private static final OkHttpClient client = new OkHttpClient();

    public static final MediaType JSON = MediaType.get("application/json;charset=utf-8");


    public static String doJsonPost(String baseUrl, String url, Object o) {
        String jsonStr= "";
        if (o != null){
            jsonStr =GsonUtils.toJson(o);
        }
        RequestBody requestBody = RequestBody.create(JSON,jsonStr);
        Request.Builder builder = getBuilder(baseUrl, url);
        Request request = builder.post(requestBody).build();
        //同步请求并获取Response
        try (Response response = client.newCall(request).execute()) {
            String body = response.body().string();
            //校验并返回
            if (response.isSuccessful()) {
                Log.i("请求结果=========================================>", body);
                String replace = body.replace("\\", "");
                Log.e("request", replace);
//                replace = replace.substring(1, replace.length() - 1);
//                Log.e("request", replace);
                return replace;
            } else {
                throw new IOException("OKHttpClientApi post response： " + response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理post请求，兼容原httpClient请求
     *
     * @param baseUrl
     * @param url
     * @param nvp
     * @param headers
     * @return
     * @throws Exception
     */
    public static String post(String baseUrl, String url, List<BasicNameValuePair> nvp, Header... headers) {
        //Request build对象
        Request.Builder builder = getBuilder(baseUrl, url);
        //处理headers
        doHeaders(builder, headers);
        //处理请求参数
        doPostRequestBody(builder, nvp);
        //创建Request
        Request request = builder.build();
        //同步请求并获取Response
        try (Response response = client.newCall(request).execute()) {
            String body = response.body().string();
            //校验并返回
            if (response.isSuccessful()) {
                Log.i("请求结果=========================================>", body);
                return body;
            } else {
                throw new IOException("OKHttpClientApi post response： " + response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理get请求，兼容原httpClient请求
     *
     * @param baseUrl
     * @param url
     * @param nvp
     * @param headers
     * @param cookies
     * @return
     * @throws Exception
     */
    public static String get(String baseUrl, String url, List<BasicNameValuePair> nvp, List<Header> headers, List<Cookie> cookies) {

        //Request build对象，get请求没有method方法，默认是PUT方式请求，直接在URL做参数处理
        Request.Builder builder;
        try {
            if(ObjectUtils.isNotEmpty(nvp) ){

                builder = getBuilder(baseUrl, url + (url.contains("?") ? "&" : "?") + EntityUtils.toString(new UrlEncodedFormEntity(nvp, "UTF-8")));
            }else{
                builder = getBuilder(baseUrl, url);
            }
        } catch (IOException | ParseException e) {
            throw new RuntimeException(e);
        }
        builder.get();
        //处理headers
        doHeaders(headers, builder);
        //创建Request
        Request request = builder.build();
        //处理cookies
        doCookies(cookies, request, client);
        //同步请求并获取Response
        try (Response response = client.newCall(request).execute()) {
            String body = response.body().string();
            //校验并返回
            if (response.isSuccessful()) {
               // Log.i("请求结果=========================================>", body);
                return body;
            } else {
                throw new IOException("OKHttpClientApi post response： " + response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * post请求参数写入Request.Builder
     *
     * @param builder
     * @param nvp
     */
    private static void doPostRequestBody(Request.Builder builder, List<BasicNameValuePair> nvp) {
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        if (!CollectionUtils.isEmpty(nvp)) {
            for (NameValuePair bean : nvp) {
                bodyBuilder.add(bean.getName(), bean.getValue());
            }
            builder.post(bodyBuilder.build());
        } else {
            builder.post(null);
        }
    }

    /**
     * 获取Request.Builder
     *
     * @param baseUrl
     * @param url
     * @return
     */
    private static Request.Builder getBuilder(String baseUrl, String url) {
        Log.i("请求地址============================>", String.format("%s%s", baseUrl, url));
        return new Request.Builder().url(String.format("%s%s", baseUrl, url));
    }

    /**
     * 处理请求cookies
     *
     * @param cookies
     * @param request
     * @param client
     */
    private static void doCookies(List<Cookie> cookies, Request request, OkHttpClient client) {
        if (!CollectionUtils.isEmpty(cookies)) {
            client.cookieJar().saveFromResponse(request.url(), convertCookies(cookies));
        }
    }

    /**
     * 处理请求headers
     *
     * @param headers
     * @param builder
     */
    private static void doHeaders(List<Header> headers, Request.Builder builder) {
        if (!CollectionUtils.isEmpty(headers)) {
            Headers.Builder headeBuilder = new Headers.Builder();
            for (Header header : headers) {
                headeBuilder.add(header.name.string(StandardCharsets.UTF_8), header.value.string(StandardCharsets.UTF_8));
            }
            builder.headers(headeBuilder.build());
        }
    }

    /**
     * 处理请求headers
     *
     * @param headers
     * @param builder
     */
    private static void doHeaders(Request.Builder builder, Header[] headers) {
        if (headers != null && headers.length > 0) {
            Headers.Builder headeBuilder = new Headers.Builder();
            for (Header header : headers) {
                headeBuilder.add(header.name.string(StandardCharsets.UTF_8), header.value.string(StandardCharsets.UTF_8));
            }
            builder.headers(headeBuilder.build());
        }
    }

    /**
     * cookie转化
     *
     * @param cookies
     * @return
     */
    private static List<Cookie> convertCookies(List<Cookie> cookies) {
        List<Cookie> list = new ArrayList<>();
        Cookie.Builder builder;
        for (Cookie cookie : cookies) {
            builder = new Cookie.Builder();
            builder.name(cookie.name())
                    .domain(cookie.domain())
                    .expiresAt(cookie.expiresAt())
                    .path(cookie.path())
                    .value(cookie.value());
            if (cookie.secure()) {
                builder.secure();
            }
            list.add(builder.build());
        }
        return list;
    }

}